package com.onlinelibrary.activities.commentsettings;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Application;
import android.content.Intent;

import androidx.annotation.NonNull;
import androidx.databinding.BindingAdapter;
import androidx.lifecycle.AndroidViewModel;

import com.google.android.material.tabs.TabLayout;
import com.onlinelibrary.activities.App;
import com.onlinelibrary.activities.reply.ReplyActivity;
import com.onlinelibrary.adapter.CommentAdapter;
import com.onlinelibrary.bean.CRBean;
import com.onlinelibrary.databinding.ActivityCommentsettingsBinding;
import com.onlinelibrary.utils.Http;
import com.onlinelibrary.view.PullingLayout;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class CommentSettingsVM extends AndroidViewModel {
    private static int nowPos=0;
    private static int count=0;//all of comments,does not visible comments.
    private static final List<CRBean> data=new ArrayList<>();
    @SuppressLint("StaticFieldLeak")
    private static CommentSettingsActivity commentSettingsActivity;
    @SuppressLint("StaticFieldLeak")
    private static ActivityCommentsettingsBinding binding;
    public CommentSettingsVM(@NonNull @NotNull Application application) {
        super(application);
    }
    public void setBinding(ActivityCommentsettingsBinding binding, CommentSettingsActivity commentSettingsActivity) {
        CommentSettingsVM.binding=binding;
        CommentSettingsVM.commentSettingsActivity=commentSettingsActivity;
        binding.setAdp(new CommentAdapter(commentSettingsActivity,data));
        binding.commentSettingsList.setOnItemClickListener((parent, view, position, id) -> {
            CRBean bean = data.get(position);
            String[] items=new String[]{"查看",(nowPos==0)?"隐藏":"公开","删除"};
            AlertDialog.Builder dialog=new AlertDialog.Builder(commentSettingsActivity);
            dialog.setTitle("请选择").setItems(items,(dialog1, which) -> {
                switch (items[which]){
                    case "查看":
                        App.commentContent=bean.content;
                        App.commentName= bean.name;
                        App.commentTime=bean.time;
                        commentSettingsActivity.startActivity(new Intent(commentSettingsActivity, ReplyActivity.class));
                        break;
                    case "隐藏":
                        Http.get("comment/?type=hide_comment&name=" + bean.name + "&time=" + bean.time, new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {
                                refresh(null);
                            }
                            @Override
                            public void onResponse(Call call, Response response) throws IOException {
                                refresh(null);
                            }
                        });
                        break;
                    case "公开":
                        Http.get("comment/?type=public_comment&name=" + bean.name + "&time=" + bean.time, new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {
                                refresh(null);
                            }
                            @Override
                            public void onResponse(Call call, Response response) throws IOException {
                                refresh(null);
                            }
                        });
                        break;
                    case "删除":
                        AlertDialog.Builder dia=new AlertDialog.Builder(commentSettingsActivity);
                        dia.setTitle("提示").setMessage("确定删除吗？").setPositiveButton("删除", (dialog11, which1) -> Http.get("comment/?type=delete_comment&name="+bean.name+"&time="+bean.time, new Callback() {
                            @Override
                            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                                refresh(null);
                            }
                            @Override
                            public void onResponse(@NotNull Call call, @NotNull Response response) {
                                refresh(null);
                            }})).setNeutralButton("关闭",null).show();
                }
            }).show();

        });
        refresh(null);
    }
    @BindingAdapter("bindTab")
    public static void bindTab(TabLayout tabLayout,CommentSettingsVM vm){
        tabLayout.addTab(tabLayout.newTab().setText("用户可见评论"));
        tabLayout.addTab(tabLayout.newTab().setText("已隐藏的评论"));
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                nowPos = tab.getPosition();
                refresh(null);
            }
            @Override
            public void onTabUnselected(TabLayout.Tab tab) { }
            @Override
            public void onTabReselected(TabLayout.Tab tab) { }
        });
    }
    @BindingAdapter("bindPull")
    public static void bindPull(PullingLayout pullingLayout, CommentSettingsVM vm){
        pullingLayout.setPullDownEnabled(true);
        pullingLayout.setOnRefreshListener(pullToRefreshLayout -> refresh(pullingLayout));
        pullingLayout.setPullUpEnabled(true);
        pullingLayout.setOnLoadMoreListener(pullToLoadMoreLayout -> {
            String commentType="";
            if (nowPos==0){
                commentType="visible";
            }else {
                commentType="invisible";
            }
            Http.get("comment/?commentType="+commentType+"&type=get_comment&start="+count+"&end="+(count+20), new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                    commentSettingsActivity.runOnUiThread(() -> pullToLoadMoreLayout.loadmoreFinish(1));
                }
                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    try {
                        JSONObject res = new JSONObject(response.body().string());
                        if (res.getString("data").equals("No Comment")){
                            commentSettingsActivity.runOnUiThread(() -> pullToLoadMoreLayout.loadmoreFinish(2));
                        }else {
                            JSONArray ja = res.getJSONArray("data");
                            for (int i = 0; i < ja.length(); i++){
                                JSONObject jo = ja.getJSONObject(i);
                                data.add(new CRBean(true,jo.getString("time"),jo.getString("name"),jo.getString("content"),jo.getString("email")));
                            }
                            commentSettingsActivity.runOnUiThread(() -> {
                                count=count+ja.length();
                                binding.getAdp().notifyDataSetChanged();
                                pullToLoadMoreLayout.loadmoreFinish(0);
                            });
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        });
    }
    private static void refresh( PullingLayout pullingLayout) {
        count=0;
        data.clear();
        String commentType="";
        if (nowPos==0){
            commentType="visible";
        }else {
            commentType="invisible";
        }
        Http.get("comment/?type=get_comment&start=0&end=20&commentType="+commentType, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                commentSettingsActivity.runOnUiThread(() -> {
                    if (pullingLayout!=null){
                        pullingLayout.refreshFinish(1);
                        pullingLayout.loadmoreFinish(1);
                    }
                });
            }
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                try {
                    JSONObject res = new JSONObject(response.body().string());
                    if (res.getString("data").equals("No Comment")){
                        commentSettingsActivity.runOnUiThread(() -> {
                            if (pullingLayout!=null){
                                pullingLayout.refreshFinish(2);
                                pullingLayout.loadmoreFinish(2);
                            }
                        });
                    }else {
                        JSONArray ja = res.getJSONArray("data");
                        for (int i = 0; i < ja.length(); i++) {
                            JSONObject jo = ja.getJSONObject(i);
                            data.add(new CRBean(true,jo.getString("time"),jo.getString("name"),jo.getString("content"),jo.getString("email")));
                        }
                        commentSettingsActivity.runOnUiThread(() -> {
                            count=count+ja.length();
                            binding.getAdp().notifyDataSetChanged();
                            if (pullingLayout!=null){
                                pullingLayout.refreshFinish(0);
                                pullingLayout.loadmoreFinish(0);
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}